package com.huaxin.hxcloud.find;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.huaxin.hxcloud.R;

import java.util.ArrayList;
import java.util.List;

/**
 *
 */
public class SearchResultFragment extends Fragment implements IsearchModel {

    private SearchModel searchModel;
    private SearchAdapter mSearchAdapter;
    private Context mContext;
    private RecyclerView mRecyclerView;

    private OnSearchResultItemClickListenner itemClickListenner;

    private List<FindSearchResultBean> resultList = new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_search_result, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        mRecyclerView = (RecyclerView) view.findViewById(R.id.search_result_list);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mSearchAdapter = new SearchAdapter(mContext,resultList,itemClickListenner);
        mRecyclerView.setAdapter(mSearchAdapter);

    }

    @Override
    public void onAttach(Context context) {
        this.mContext = context;
        if ((context instanceof OnSearchResultItemClickListenner)) {
            this.itemClickListenner= (OnSearchResultItemClickListenner) context;
        } else {
            throw new RuntimeException("you must implement interface " +
                    "OnSearchResultItemClickListenner");
        }
        super.onAttach(context);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    public void requestDatas(int type,String keyword) {
        //searchModel使用单例模式
        if (searchModel == null) {
            searchModel = new SearchModel(this);//初始化searchModel
        }
        //清空原有的数据
        resultList.clear();
        //请求数据
        searchModel.requestDatas(type, keyword);
    }

    @Override
    public void onDataLoadFinished(List<FindSearchResultBean> findSearchBeens) {
        if (findSearchBeens==null)
            return;
        //加入新的数据
        resultList.addAll(findSearchBeens);
        mSearchAdapter.notifyDataSetChanged();
    }

    public void clearData(){
        resultList.clear();
        if (mSearchAdapter==null)
            return;
        mSearchAdapter.notifyDataSetChanged();
    }
    public interface OnSearchResultItemClickListenner{
        void onItemClick(int type,FindSearchResultBean resultBean,int position);
    }
}
